package com.imooc.o2o.util;

import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Positions;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

public class ImageUtil {
    public static String generateThumbnail(InputStream shopImgInputStream, String fileName, String targetAddr) {
        String realFileName = FileUtil.getRandomFileName();
        String extension = getFileExtension(fileName);
        makeDirPath(targetAddr);
        String relativeAddr = targetAddr + realFileName + extension;
        File dest = new File(FileUtil.getImgBasePath() + relativeAddr);
        try {
            Thumbnails.of(shopImgInputStream).size(200, 200).outputQuality(0.25f).toFile(dest);
        } catch (IOException e) {
            throw new RuntimeException("创建缩略图失败：" + e.toString());
        }
        return relativeAddr;
    }
    public static void main(String[] args) throws IOException {
//        String basePath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
//        System.out.println(basePath);
//        Thumbnails.of(new File("/Users/zhang/crazy/o2o/src/main/resources/0.jpeg"))
//        .size(200,200)
//        .watermark(Positions.BOTTOM_RIGHT,ImageIO.read(new File(basePath+"/shuiyin.png")),0.25f)
//        .outputQuality(0.8f)
//        .toFile("/Users/zhang/crazy/o2o/src/main/resources/1.jpeg");
    }
    private static void makeDirPath(String targetAddr) {
        String realFileParentPath = FileUtil.getImgBasePath() + targetAddr;
        File dirPath = new File(realFileParentPath);
        if (!dirPath.exists()) {
            dirPath.mkdirs();
        }
    }
    private static String getFileExtension(String fileName) {
        return fileName.substring(fileName.lastIndexOf("."));
    }
}
